<?php

class Client {
    private $client;

    public function __construct() {
        $this->client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);

        $this->client->on('Connect', array($this, 'onConnect'));
        $this->client->on('Receive', array($this, 'onReceive'));
        $this->client->on('Close', array($this, 'onClose'));
        $this->client->on('Error', array($this, 'onError'));
    }

    public function connect() {
        $fp = $this->client->connect('127.0.0.1', 9501, 1);
        if ( !$fp ) {
            echo "error: {$fp->errMsg}[{$fp->errCode}]\n";
            return;
        }
    }

    public function onReceive($cli, $data) {
        echo "get message from server: {$data}\n";
    }

    public function onConnect($cli) {
        fwrite(STDOUT, 'eNTER MSG:');
        swoole_event_add(STDIN, function($fp){
            global $client;
            fwrite(STDOUT, 'ENTER MSG:');
            $msg = trim(fgets(STDIN));
            $client->send($msg);
        });
    }

    public function onClose($cli) {
        echo "Client close connection\n";
    }

    public function onError() {
      }
        public function send($data) {
            $this->client->send( $data );
              }
                public function isConnected() {
                    return $this->client->isConnected();
                      }

}

$client = new Client();
$client->connect();
